import Compressor from 'image-compressor.js'
import QrCode from "qrcode-decoder";

export const getBase64 = (data) => {
  return new Promise((resolve, reject) => {
    new Compressor(data, {
      quality: 0.6,
      checkOrientation: false,
      convertSize: 5000000,
      maxHeight: 1024,
      minWidth: 768,
      drew(context, canvas) {
        const base64Image = canvas.toDataURL('image/jpeg')
        resolve(base64Image)
      },
      error() {
        reject()
      }
    })
  })
}

// 解码
export async function decodeQrCode(url) {
    // var url = null;
    // if (window.createObjectURL != undefined) {
    //   // basic
    //   url = window.createObjectURL(file);
    // } else if (window.URL != undefined) {
    //   // mozilla(firefox)
    //   url = window.URL.createObjectURL(file);
    // } else if (window.webkitURL != undefined) {
    //   // webkit or chrome
    //   url = window.webkitURL.createObjectURL(file);
    // }
    const qr = new QrCode();
    let result = await qr.decodeFromImage(url)
    if (result && result.data) {
      return result.data
    }
    result = await otherQrcode(url)
    if (result) {
      return result
    }
    return false
}

// 使用reqrcode解码
const otherQrcode = (url) => {
  return new Promise((resolve) => {
    qrcode.decode(url);
    qrcode.callback = function (imgMsg) {
      if (
        imgMsg == "error decoding QR Code" ||
        imgMsg == "Failed to load the image" ||
        imgMsg == "Couldn't find enough finder patterns (found 0)"
      ) {
        resolve(false)
      } else {
        if (imgMsg.startsWith("http")) {
          // 链接形式不处理
          resolve(false)
          return;
        }
        resolve(imgMsg)
      }
    };
  })
}

export const changeHttpImageUrl = (httpUrl) => {
  var target =
    window.location.protocol === "https:"
      ? "https://groupbuy.xiongmaodangao.com/"
      : "http://groupbuy.xiongmaodangao.com/";
  return httpUrl.replace("http://oss.xiongmaodangao.com/", target);
}
